//贪食蛇内容
{
    //用属性名获取DOM对象
    function getElementByAttr(tag, attr1, value1, attr2, value2) {
        var aElements = document.getElementsByTagName(tag);
        var aEle = [];
        if (attr2 === undefined) {
            for (var i = 0; i < aElements.length; i++) {
                if (aElements[i].getAttribute(attr1) == value1) aEle.push(aElements[i]);
            }
        } else if (typeof value1 === "object") {
            for (var i = 0; i < aElements.length; i++) {
                if (value1.includes(aElements[i].getAttribute(attr1)) && value2.includes(aElements[i].getAttribute(attr2))) aEle.push(aElements[i]);
            }
        } else {
            for (var i = 0; i < aElements.length; i++) {
                if (aElements[i].getAttribute(attr1) == value1 && aElements[i].getAttribute(attr2) == value2) aEle.push(aElements[i]);
            }
        }

        return aEle;
    }
    const gameBox = document.querySelector(".gameBox");
    const prompt = document.querySelector(".prompt");
    const inputAll = document.querySelectorAll("input");
    const boxSize = 30;
    let flag = "top";
    let taildirection = [];
    let food;
    let speed = 250;
    let res = 0;
    let aa = 0;
    let start = 0;
    let timeOut = "yes";
    let over = 0;
    let mapflag = "普通";
    inputAll[1].value = mapflag;
    let velocityflag = "简单";
    inputAll[2].value = velocityflag;
    let fractionflag = 0;
    inputAll[3].value = fractionflag;
    let form = document.querySelector("form");
    //初始蛇
    let snake = [
        {
            x: 25,
            y: 28,
            d: "top",
        },
        {
            x: 26,
            y: 28,
            d: "top",
        },
        {
            x: 27,
            y: 28,
            d: "top",
        },
        {
            x: 28,
            y: 28,
            d: "top",
        },
    ];

    // 绘制地图像素格
    for (let i = 1; i < boxSize + 1; i++) {
        gameBox.innerHTML += `
                <div class="col">${(function f1() {
                    var arr = [];
                    for (let j = 1; j < boxSize + 1; j++) {
                        var a = `<div data-x="${j}" data-y="${i}" class="iconfont"></div>`;
                        arr.push(a);
                    }
                    return arr;
                })().join("")}
                </div>
            `;
    }

    // 绘制墙面
    let drawWall = () => {
        let wallDiv = document.querySelectorAll(".wall");
        wallDiv.forEach((item) => {
            item.innerHTML = `<span>&#xe78a;</span>`;
        });
    };

    // 删除墙面
    let delwWall = () => {
        let wallDiv = document.querySelectorAll(".wall");
        wallDiv.forEach((item) => {
            item.innerHTML = "";
            item.classList.remove("wall");
        });
    };

    //绘制蛇
    let drawsnake = () => {
        //删除蛇
        let oldSnake = document.querySelectorAll(".snakeBodyTop ,.snakeBodyTop,.snakeBodyLeft,.snakeBodyTopLeft,.snakeBodyTopRight,.snakeBodyBottomLeft,.snakeBodyBottomRight,.snakeHeadTop,.snakeHeadBottom,.snakeHeadLeft,.snakeHeadRight,.snakeTailTop,.snakeTailBottom,.snakeTailLeft,.snakeTailRight");
        oldSnake.forEach((item) => {
            item.classList.remove("snakeBodyTop", "snakeBodyTop", "snakeBodyLeft", "snakeBodyTopLeft", "snakeBodyTopRight", "snakeBodyBottomLeft", "snakeBodyBottomRight", "snakeHeadTop", "snakeHeadBottom", "snakeHeadLeft", "snakeHeadRight", "snakeTailTop", "snakeTailBottom", "snakeTailLeft", "snakeTailRight");
        });
        //绘制蛇
        snake.forEach((item, index) => {
            let snakeOne = getElementByAttr("div", "data-x", item.x, "data-y", item.y)[0];
            if (index === 0) {
                if (snake[index].d === "top") snakeOne.classList.add("snakeHeadTop");
                else if (snake[index].d === "bottom") snakeOne.classList.add("snakeHeadBottom");
                else if (snake[index].d === "left") snakeOne.classList.add("snakeHeadLeft");
                else if (snake[index].d === "right") snakeOne.classList.add("snakeHeadRight");
            } else if (index === snake.length - 1) {
                if (snake[index].d === "top") snakeOne.classList.add("snakeTailTop");
                else if (snake[index].d === "bottom") snakeOne.classList.add("snakeTailBottom");
                else if (snake[index].d === "left") snakeOne.classList.add("snakeTailLeft");
                else if (snake[index].d === "right") snakeOne.classList.add("snakeTailRight");
            } else {
                if (snake[index].d === "top" || snake[index].d === "bottom") snakeOne.classList.add("snakeBodyTop");
                else if (snake[index].d == "left" || snake[index].d === "right") snakeOne.classList.add("snakeBodyLeft");
                else if (snake[index].d === "topleft") snakeOne.classList.add("snakeBodyTopLeft");
                else if (snake[index].d === "topright") snakeOne.classList.add("snakeBodyTopRight");
                else if (snake[index].d === "bottomleft") snakeOne.classList.add("snakeBodyBottomLeft");
                else if (snake[index].d === "bottomright") snakeOne.classList.add("snakeBodyBottomRight");
            }
        });
    };

    //默认地图
    let nomMap = () => {
        let x1Div = getElementByAttr("div", "data-x", 1);
        let y1Div = getElementByAttr("div", "data-y", 1);
        let x30Div = getElementByAttr("div", "data-x", 30);
        let y30Div = getElementByAttr("div", "data-y", 30);
        let xy130Div = [...x1Div, ...y1Div, ...x30Div, ...y30Div];
        xy130Div.forEach((item) => {
            item.classList.add("wall");
        });
    };

    // 困难地图
    let hardMap = () => {
        let hardDiv = [];
        hardDiv.push(...getElementByAttr("div", "data-x", ["15", "16"], "data-y", ["5", "6", "7", "8", "9", "10", "11", "20", "21", "22", "23", "24", "25", "26"]));
        hardDiv.push(...getElementByAttr("div", "data-x", ["5", "6", "7", "8", "9", "10", "11", "20", "21", "22", "23", "24", "25", "26"], "data-y", ["15", "16"]));
        hardDiv.forEach((item) => {
            item.classList.add("wall");
        });
    };

    // 初始化移动方向
    let moveX = -1;
    let moveY = 0;
    let directionFlag = "top";
    let direction = "top";

    // 移动蛇
    let moveSnake = () => {
        for (let i = snake.length - 1; i > 0; i--) {
            snake[i] = { ...snake[i - 1] };
        }
        snake[0].x += moveX;
        if (snake[0].x <= 0) {
            snake[0].x = 30;
        }
        if (snake[0].x >= 31) {
            snake[0].x = 1;
        }
        snake[0].y += moveY;

        if (snake[0].y <= 0) {
            snake[0].y = 30;
        }
        if (snake[0].y >= 31) {
            snake[0].y = 1;
        }
        if (flag === "bottomleft") snake[1].d = "bottomleft";
        else if (flag === "topleft") snake[1].d = "topleft";
        else if (flag === "bottomright") snake[1].d = "bottomright";
        else if (flag === "topright") snake[1].d = "topright";
        if (snake[snake.length - 1].d === "bottomleft" || snake[snake.length - 1].d === "topleft" || snake[snake.length - 1].d === "bottomright" || snake[snake.length - 1].d === "topright") {
            snake[snake.length - 1].d = taildirection[0];
            taildirection.shift();
        }
        flag = "";
    };

    //改变蛇的方向
    document.onkeydown = function (e) {
        console.log(e);
        if (e.keyCode === 32) {
            if (over === 0) {
                if (timeOut == "no") {
                    clearInterval(times);
                    timeOut = "yes";
                    prompt.style.display = "block";
                } else if (timeOut == "yes") {
                    times = setInterval(() => {
                        if (taildirection[aa] == "00") {
                            taildirection.pop();
                        }
                        taildirection.forEach((item, index) => {
                            if (taildirection[index] == "00") {
                                taildirection.splice(index, 1);
                            }
                        });
                        stopWall();
                        moveSnake();
                        drawsnake();
                        eatFood();
                        foodRandom();
                        taildirection.push("00");
                        aa = taildirection.length - 1;
                        direction = directionFlag;
                        prompt.style.display = "none";
                    }, speed);
                    timeOut = "no";
                }
            }
        }
        // let length= taildirection.length
        if (e.keyCode === 37 || e.keyCode === 65) {
            if (direction !== "right") {
                moveX = 0;
                moveY = -1;
                snake[0].d = "left";
                if (direction === "top") {
                    flag = "bottomleft";
                    taildirection[aa] = "left";
                } else if (direction === "bottom") {
                    flag = "topleft";
                    taildirection[aa] = "left";
                } else if (direction === "left") {
                    flag = "";
                    taildirection[aa] = "00";
                }
                directionFlag = "left";
            }
        } else if (e.keyCode === 38 || e.keyCode === 87) {
            if (direction !== "bottom") {
                moveX = -1;
                moveY = 0;
                snake[0].d = "top";
                if (direction === "left") {
                    flag = "topright";
                    taildirection[aa] = "top";
                } else if (direction === "right") {
                    flag = "topleft";
                    taildirection[aa] = "top";
                } else if (direction === "top") {
                    flag = "";
                    taildirection[aa] = "00";
                }
                directionFlag = "top";
            }
        } else if (e.keyCode === 39 || e.keyCode === 68) {
            if (direction !== "left") {
                moveX = 0;
                moveY = 1;
                snake[0].d = "right";
                if (direction === "top") {
                    flag = "bottomright";
                    taildirection[aa] = "right";
                } else if (direction === "bottom") {
                    flag = "topright";
                    taildirection[aa] = "right";
                } else if (direction === "right") {
                    flag = "";
                    taildirection[aa] = "00";
                }
                directionFlag = "right";
            }
        } else if (e.keyCode === 40 || e.keyCode === 83) {
            if (direction !== "top") {
                moveX = 1;
                moveY = 0;
                snake[0].d = "bottom";
                if (direction === "left") {
                    flag = "bottomright";
                    taildirection[aa] = "bottom";
                } else if (direction === "right") {
                    flag = "bottomleft";
                    taildirection[aa] = "bottom";
                } else if (direction === "bottom") {
                    flag = "";
                    taildirection[aa] = "00";
                }
                directionFlag = "bottom";
            }
        }
    };

    // 撞墙判定
    let stopWall = () => {
        let sankeHead = document.querySelectorAll(".snakeHeadTop,.snakeHeadBottom,.snakeHeadLeft,.snakeHeadRight")[0];
        let a = sankeHead.className;
        if (!(a === "iconfont" || a === "iconfont food" || a === "iconfont snakeHeadTop" || a === "iconfont snakeHeadBottom" || a === "iconfont snakeHeadLeft" || a === "iconfont snakeHeadRight")) {
            clearInterval(times);
            over = 1;
            form.style.display = "flex";
        }
    };

    // 吃食物判断
    let eatFood = () => {
        let sankeHead = document.querySelectorAll(".snakeHeadTop,.snakeHeadBottom,.snakeHeadLeft,.snakeHeadRight")[0];
        let sankeTail = { ...snake[snake.length - 1] };
        if (sankeHead.classList.contains("food")) {
            snake.push(sankeTail);
            food.classList.remove("food");
            document.querySelector(".res span").innerHTML = ++res;
            fractionflag = res;
            inputAll[3].value = fractionflag;
        }
    };

    //生成食物
    let foodRandom = () => {
        food = document.querySelector(".food");
        if (!food) {
            let foodX = Math.floor(Math.random() * (boxSize - 2) + 2);
            let foodY = Math.floor(Math.random() * (boxSize - 2) + 2);
            let foodXY = getElementByAttr("div", "data-x", foodX, "data-y", foodY)[0];
            if (foodXY.className === "iconfont") {
                foodXY.classList.add("food");
            } else {
                foodRandom();
            }
        }
    };
    drawsnake();
    nomMap();
    drawWall();
    let times;

    //右侧模块
    {
        let speedChoice = document.querySelectorAll(".speed .choice div");
        let mapChoice = document.querySelectorAll(".map .choice div");

        //选择器通用函数
        let chicefn = function (type, num) {
            if (start == 0) {
                if (type === "speed") {
                    let so = document.querySelector(".speed .on");
                    so ? so.classList.remove("on") : "";
                    if (num == 0) {
                        speed = 250;
                        velocityflag = "简单";
                    } else if (num == 1) {
                        speed = 150;
                        velocityflag = "普通";
                    } else if (num == 2) {
                        speed = 80;
                        velocityflag = "困难";
                    } else if (num == 3) {
                        speed = 40;
                        velocityflag = "地狱";
                    }
                    this.classList.add("on");
                    inputAll[2].value = velocityflag;
                }

                if (type === "map") {
                    let gameBox = document.querySelector(".gameBox");
                    let mo = document.querySelector(".map .on");
                    mo ? mo.classList.remove("on") : "";
                    delwWall();
                    if (num == 0) {
                        nomMap();
                        mapflag = "普通";
                    } else if (num == 1) {
                        nomMap();
                        hardMap();
                        mapflag = "困难";
                    } else if (num == 2) {
                        mapflag = "无边框";
                    }
                    drawWall();
                    this.classList.add("on");
                    inputAll[1].value = mapflag;
                }
            }
        };

        //速度按钮绑定
        speedChoice.forEach(function (item, index) {
            item.onclick = function () {
                chicefn.call(this, "speed", index);
            };
        });
        //地图按钮绑定
        mapChoice.forEach(function (item, index) {
            item.onclick = function () {
                chicefn.call(this, "map", index);
            };
        });

        let btns = document.querySelectorAll(".btns div");
        btns[0].onclick = function (params) {
            if (timeOut == "yes") {
                if (over === 0) {
                    times = setInterval(() => {
                        if (taildirection[aa] == "00") {
                            taildirection.pop();
                        }
                        taildirection.forEach((item, index) => {
                            if (taildirection[index] == "00") {
                                taildirection.splice(index, 1);
                            }
                        });
                        moveSnake();
                        drawsnake();
                        eatFood();
                        foodRandom();
                        stopWall();
                        taildirection.push("00");
                        aa = taildirection.length - 1;
                        direction = directionFlag;
                        start = 1;
                        prompt.style.display = "none";
                        timeOut = "no";
                    }, speed);
                }
            }
        };
        btns[1].onclick = function () {
            if (over === 0) {
                clearInterval(times);
                prompt.style.display = "block";
                timeOut = "yes";
            }
        };
        btns[2].onclick = function () {
            location.reload();
        };
        let re = document.querySelector("#re");
        re.onclick = () => {
            location.reload();
        };
    }
}
